import json
from datetime import datetime, timedelta
from django.utils import timezone

from django.db import connections, connection
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from .models import User, Patient, PatientMeal
from django.db import IntegrityError
from .utils import parse_request_data

from app01.models import Patient
from app01.sql import save_patient_info, save_bolus_record, save_meal_record
from app01.basal_adjustment import get_basal_recommendations
from django.conf import settings
import os


# Create your views here.
@api_view(['POST'])
@permission_classes([AllowAny])
@csrf_exempt
def setPatientInfo(request):
    try:
        data = json.loads(request.body.decode('utf-8'))
        full_name = data.get("fullName")
        patient_number = data.get("patientNumber")
        age = data.get("age")
        weight = data.get("weight")
        tdd = data.get("tdd")  # TDD参数
        basal_insulin = data.get("basalInsulin")  # 基础胰岛素剂量参数
        
        print(f"Received data: {data}")  # 打印接收到的数据
        
        # 使用原生SQL避开ORM字段不匹配问题
        with connection.cursor() as cursor:
            # 检查患者是否已存在
            cursor.execute(
                "SELECT COUNT(*) FROM patient_info WHERE patient_number = %s",
                [patient_number]
            )
            exists = cursor.fetchone()[0] > 0
            
            if exists:
                # 更新现有患者信息
                cursor.execute(
                    """
                    UPDATE patient_info 
                    SET full_name = %s, age = %s, weight = %s, tdd = %s, basal_insulin = %s
                    WHERE patient_number = %s
                    """,
                    [full_name, age, weight, tdd, basal_insulin, patient_number]
                )
                is_created = False
            else:
                # 插入新患者信息
                cursor.execute(
                    """
                    INSERT INTO patient_info 
                    (full_name, patient_number, age, weight, tdd, basal_insulin,
                    enteral_nutrition, parenteral_nutrition)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                    """,
                    [full_name, patient_number, age, weight, tdd, basal_insulin, False, False]
                )
                is_created = True
                
        # 如果是首次创建患者记录
        if is_created:
            # 动态表名为患者编号（patient_number）
            table_name = f'cgm_{patient_number}'  # 表名为患者编号，避免与其他表冲突

            # 检查表是否已经存在
            with connection.cursor() as cursor:
                cursor.execute(f"""
                    SELECT * 
                    FROM information_schema.tables 
                    WHERE table_name = '{table_name}';
                """)
                result = cursor.fetchone()

                # 如果表不存在，创建表
                if not result:
                    create_table_sql = f"""
                    CREATE TABLE {table_name} (
                        sg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,  -- 时间戳字段
                        sgv INTEGER NOT NULL  -- 整数字段
                    );
                    """
                    cursor.execute(create_table_sql)  # 执行 SQL 创建表
                    return Response({"status": "success", "message": "Patient info saved successfully."}, status=200)
                else:
                    return Response({"status": "success", "message": "Patient info saved successfully but table already exists."}, status=200)

        else:
            return Response({"status": "success", "message": "Patient info updated successfully."}, status=200)

    except Exception as e:
        import traceback
        print(f"Error in setPatientInfo: {str(e)}")
        print(traceback.format_exc())
        return Response({"status": "error", "message": f"An error occurred: {str(e)}"}, status=500)



@csrf_exempt
def setBolus(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))

        patient_number = data.get("patientNumber")
        bolus = data.get("bolus")

        if not patient_number or bolus is None:
            return JsonResponse({"status": "error", "message": "Missing patient number or bolus value."}, status=400)

        # 保存数据到数据库
        success, error_message = save_bolus_record(patient_number, bolus)

        if success:
            return JsonResponse({"status": "success", "message": "Bolus record saved successfully."}, status=200)
        else:
            return JsonResponse({"status": "error", "message": error_message}, status=500)

    return JsonResponse({"status": "error", "message": "Invalid request method."}, status=400)


@csrf_exempt
@api_view(['POST', 'GET'])
def getPatient(request):
    try:
        # 获取所有患者的信息，包括前端需要的所有字段
        patients = Patient.objects.all().values(
            'patient_number', 'full_name', 'age', 'weight', 'tdd', 'basal_insulin'
        )

        # 将查询结果转换为前端期望的格式
        patient_list = []
        for p in patients:
            patient_list.append({
                'patientNumber': p['patient_number'],
                'fullName': p['full_name'],
                'age': p['age'],
                'weight': p['weight'],
                'tdd': p['tdd'],
                'basalInsulin': p['basal_insulin']
            })

        if patient_list:
            # 直接返回患者列表，不包含额外的status和patients包装
            return JsonResponse(patient_list, safe=False, status=200)
        else:
            # 如果没有患者，返回空列表
            return JsonResponse([], safe=False, status=200)

    except Exception as e:
        print(f"Error in getPatient: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return JsonResponse({"status": "error", "message": str(e)}, status=500)

@csrf_exempt
@api_view(['POST', 'DELETE'])
def deletePatient(request):
    if request.method == 'POST':
        # 从请求体中获取 JSON 数据
        try:
            data = json.loads(request.body.decode('utf-8'))
            patient_number = data.get('patientNumber')

            if not patient_number:
                return JsonResponse({"status": "error", "message": "Patient number is required."}, status=400)

            try:
                # 查找并删除 Patient 表中的患者记录
                patient = Patient.objects.get(patient_number=patient_number)
                patient.delete()

                return JsonResponse({"status": "success", "message": f"Patient {patient_number} deleted successfully."}, status=200)

            except Patient.DoesNotExist:
                return JsonResponse({"status": "error", "message": "Patient not found."}, status=404)

        except json.JSONDecodeError:
            return JsonResponse({"status": "error", "message": "Invalid JSON format."}, status=400)

    return JsonResponse({"status": "error", "message": "Invalid request method."}, status=400)


@csrf_exempt
@api_view(['POST', 'GET'])
def getCGM(request):
    if request.method == 'POST':
        # 解析请求体
        data = json.loads(request.body.decode('utf-8'))
        patient_number = data.get("patientNumber")

        if not patient_number:
            return JsonResponse({"status": "error", "message": "Missing patient number."}, status=400)

        # 动态构建表名，根据患者编号来查询对应的表
        table_name = f"`cgm_{patient_number}`"  # 使用反引号包裹表名，避免 SQL 错误

        try:
            # 执行原生SQL查询来获取前288条血糖记录
            with connections['default'].cursor() as cursor:
                cursor.execute(f"""
                    SELECT sg_date, sgv FROM {table_name}
                    ORDER BY sg_date DESC
                    LIMIT 288
                """)

                # 获取查询结果
                results = cursor.fetchall()

            if results:
                # 将每一行数据转换为字典形式，键是 sg_date（转换为字符串），值是 sgv
                blood_sugar_records = {
                    result[0].strftime('%Y-%m-%d %H:%M:%S'): result[1]  # 将 sg_date 转换为字符串
                    for result in results
                }

                return JsonResponse({"status": "success", "records": blood_sugar_records}, status=200)
            else:
                return JsonResponse({"status": "success", "message": "No data found in the table."},
                                    status=200)

        except Exception as e:
            return JsonResponse({"status": "error", "message": str(e)}, status=500)

    return JsonResponse({"status": "error", "message": "Invalid request method."}, status=400)



@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    try:
        # 打印接收到的数据以便调试
        print(f"==== 登录请求数据 ====")
        print(f"请求数据: {request.data}")
        
        # 使用工具函数解析请求数据
        data = parse_request_data(request)
        print(f"解析后的数据: {data}")
        
        username = data.get('username')
        password = data.get('password')
        
        # 记录关键参数
        print(f"用户名: {username}, 密码长度: {len(password) if password else 0}")
        
        if not username or not password:
            print("登录失败: 用户名或密码为空")
            return Response({
                'status': 'error',
                'message': '用户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 先检查用户是否存在 - 增加更详细的调试信息
            print(f"开始验证用户 {username} 是否存在")
            print(f"当前设置的AUTH_USER_MODEL: {settings.AUTH_USER_MODEL}")
            
            # 输出所有用户以便调试
            print("系统中所有用户列表:")
            all_users = User.objects.all()
            for user in all_users:
                print(f"  - ID: {user.id}, 用户名: {user.username}, 激活状态: {user.is_active}")

            # 使用不区分大小写的查询方式 
            # 首先使用__iexact进行不区分大小写的查询
            user = User.objects.filter(username__iexact=username).first()
            
            if not user:
                print(f"登录失败: 用户不存在 - {username}")
                return Response({
                    'status': 'error',
                    'message': '用户名或密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 验证密码之前先检查用户是否激活
            if not user.is_active:
                print(f"登录失败: 用户未激活 - {user.username}")
                # 自动激活用户
                user.is_active = True
                user.save()
                print(f"用户已自动激活: {user.username}")
            
            # 验证密码
            print(f"用户存在 (ID: {user.id}, 用户名: {user.username}), 开始验证密码")
            # 使用实际存储的用户名进行验证
            auth_user = authenticate(username=user.username, password=password)
            
            if auth_user is None:
                print(f"登录失败: 密码验证失败 - {user.username}")
                
                # 尝试直接使用User模型验证密码 (不通过authenticate)
                from django.contrib.auth.hashers import check_password
                if check_password(password, user.password):
                    print(f"直接密码验证成功，但authenticate失败，可能是backend问题")
                else:
                    print(f"直接密码验证也失败，密码确实不匹配")
                
                return Response({
                    'status': 'error',
                    'message': '用户名或密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)
            
            # 生成Token
            refresh = RefreshToken.for_user(auth_user)
            
            # 构建响应数据，兼容uni-app格式
            response_data = {
                'status': 'success',
                'message': '登录成功',
                'data': {
                    'token': str(refresh.access_token),
                    'user': {
                        'userId': auth_user.id,
                        'username': auth_user.username,
                        'role': auth_user.role
                    }
                }
            }
            
            print(f"登录成功: {auth_user.username}")
            response = Response(response_data, status=status.HTTP_200_OK)
            
            # 手动添加CORS响应头
            response["Access-Control-Allow-Origin"] = "*"
            response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
            response["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
            
            return response
            
        except User.DoesNotExist:
            print(f"登录失败: 用户查询异常 - {username}")
            return Response({
                'status': 'error',
                'message': '用户名或密码错误'
            }, status=status.HTTP_401_UNAUTHORIZED)
        except Exception as auth_error:
            print(f"认证过程错误: {str(auth_error)}")
            import traceback
            print(traceback.format_exc())
            
            # 数据库相关错误处理
            if "no such table" in str(auth_error).lower():
                print("数据库表不存在，可能需要执行数据库迁移")
                return Response({
                    'status': 'error',
                    'message': '系统配置错误，请联系管理员'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
            return Response({
                'status': 'error',
                'message': f'认证过程错误: {str(auth_error)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {str(e)}")
        response = Response({
            'status': 'error',
            'message': f'无效的请求格式: {str(e)}'
        }, status=status.HTTP_400_BAD_REQUEST)
        
        # 添加CORS头
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
        response["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
        
        return response
    except Exception as e:
        print(f"登录过程中发生错误: {str(e)}")
        import traceback
        print(traceback.format_exc())
        response = Response({
            'status': 'error',
            'message': '服务器内部错误，请稍后再试'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        # 添加CORS头
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
        response["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
        
        return response

@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
    try:
        # 打印接收到的数据以便调试
        print(f"==== 注册请求数据 ====")
        print(f"请求数据: {request.data}")
        
        # 使用工具函数解析请求数据
        data = parse_request_data(request)
        print(f"解析后的数据: {data}")
        
        username = data.get('username')
        password = data.get('password')
        confirm_password = data.get('confirmPassword')
        
        print(f"用户名: {username}, 密码长度: {len(password) if password else 0}")
        
        if not username or not password or not confirm_password:
            print("注册失败: 缺少必要参数")
            return Response({
                'status': 'error',
                'message': '所有字段都是必填的'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if password != confirm_password:
            print("注册失败: 两次密码不一致")
            return Response({
                'status': 'error',
                'message': '两次输入的密码不一致'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 检查用户是否存在 (不区分大小写)
            if User.objects.filter(username__iexact=username).exists():
                print(f"注册失败: 用户名已存在 (不区分大小写) - {username}")
                return Response({
                    'status': 'error',
                    'message': '用户名已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 使用数据库事务保证操作的原子性    
            from django.db import transaction
            try:
                with transaction.atomic():
                    # 创建用户
                    print(f"开始创建用户: {username}")
                    user = User.objects.create_user(
                        username=username,
                        password=password,
                        is_active=True  # 确保用户被激活
                    )
                    print(f"用户创建成功: ID={user.id}, 用户名={user.username}")
                
                # 事务提交后执行以下操作
                print(f"数据库事务已自动提交")
                
                # 输出所有用户以验证
                print("当前系统中所有用户:")
                all_users = User.objects.all()
                for u in all_users:
                    print(f"  - ID: {u.id}, 用户名: {u.username}, 是否激活: {u.is_active}")
                
                # 尝试手动验证新创建的用户
                test_auth = authenticate(username=username, password=password)
                if test_auth:
                    print(f"新创建的用户认证测试成功: {username}")
                else:
                    print(f"警告: 新创建的用户无法通过认证测试: {username}")
                    # 尝试再次从数据库加载用户以确认是否正确保存
                    try:
                        saved_user = User.objects.get(username=username)
                        print(f"用户在数据库中存在: ID={saved_user.id}, 是否激活={saved_user.is_active}")
                    except User.DoesNotExist:
                        print(f"严重错误: 刚创建的用户在数据库中不存在!")
            
                # 构建响应数据，兼容uni-app格式
                response_data = {
                    'status': 'success',
                    'message': '注册成功',
                    'data': {
                        'userId': user.id,
                        'username': user.username
                    }
                }
                
                return Response(response_data, status=status.HTTP_200_OK)
            
            except IntegrityError as ie:
                print(f"注册失败: 数据库完整性错误 - {str(ie)}")
                import traceback
                print(traceback.format_exc())
                return Response({
                    'status': 'error',
                    'message': f'用户名已存在或数据库错误: {str(ie)}'
                }, status=status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                print(f"注册过程中发生错误: {str(e)}")
                import traceback
                print(traceback.format_exc())
                
                # 数据库相关错误处理
                if "no such table" in str(e).lower():
                    print("数据库表不存在，可能需要执行数据库迁移")
                    return Response({
                        'status': 'error',
                        'message': '系统配置错误，请联系管理员'
                    }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                    
                return Response({
                    'status': 'error',
                    'message': f'创建用户时发生错误: {str(e)}'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
        except Exception as e:
            print(f"注册过程中发生未处理的错误: {str(e)}")
            import traceback
            print(traceback.format_exc())
            return Response({
                'status': 'error',
                'message': '服务器内部错误，请稍后再试'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
    except Exception as e:
        print(f"注册过程中发生未处理的错误: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return Response({
            'status': 'error',
            'message': '服务器内部错误，请稍后再试'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@csrf_exempt
def getPatientCGM(request, patient_id):
    """
    通过GET请求获取患者CGM数据
    :param request: HTTP请求对象
    :param patient_id: 患者ID
    :return: JSON响应
    """
    try:
        # 获取当前时间
        now = datetime.now()
        # 计算24小时前的时间
        twenty_four_hours_ago = now - timedelta(hours=24)
        # 动态构建表名
        table_name = f"`cgm_{patient_id}`"

        # 执行原生SQL查询来获取最近24小时的所有血糖记录
        with connections['default'].cursor() as cursor:
            cursor.execute(f"""
                SELECT sg_date, sgv FROM {table_name}
                WHERE sg_date >= %s
                ORDER BY sg_date ASC
            """, [twenty_four_hours_ago])

            # 获取查询结果
            results = cursor.fetchall()

        if results:
            # 将每一行数据转换为字典形式
            blood_sugar_records = {
                result[0].strftime('%Y-%m-%d %H:%M:%S'): result[1]
                for result in results
            }
            return JsonResponse({"status": "success", "records": blood_sugar_records}, status=200)
        else:
            return JsonResponse({"status": "success", "message": "No data found for the last 24 hours."}, status=200)

    except Exception as e:
        return JsonResponse({"status": "error", "message": str(e)}, status=500)

@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny])
def setMealRecord(request):
    try:
        data = request.data
        patient_number = data.get('patientNumber')
        meal_type = data.get('mealType')
        cho = data.get('cho')
        pre_meal_bolus = data.get('preMealBolus')
        notes = data.get('notes')
        time_str = data.get('time') # 新增：获取前端传递的时间字符串

        meal_datetime_obj = None
        if time_str:
            try:
                # 尝试解析包含秒的格式
                meal_datetime_obj = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
            except ValueError:
                try:
                    # 如果失败，尝试解析不包含秒的格式
                    meal_datetime_obj = datetime.strptime(time_str, '%Y-%m-%d %H:%M')
                except ValueError:
                    return Response({
                        "status": "error",
                        "message": "无效的时间格式，请使用 YYYY-MM-DD HH:MM:SS 或 YYYY-MM-DD HH:MM"
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # Django配置了USE_TZ=True时，天真的datetime对象在保存时通常会被认为是UTC或默认时区。
            # 如果前端发送的是本地时间且需要转换为settings.TIME_ZONE，需要更复杂的处理。
            # 此处假设前端发送的时间是期望直接存入数据库的时间（或者是UTC时间）。
            # 如果需要时区转换，可以使用 timezone.make_aware。
            # 例如: if settings.USE_TZ and meal_datetime_obj and timezone.is_naive(meal_datetime_obj):
            #           meal_datetime_obj = timezone.make_aware(meal_datetime_obj, timezone.get_current_timezone())

        if not all([patient_number, meal_type]): # CHO 和 pre_meal_bolus 可以为0，但必须存在
            # 检查 cho 和 pre_meal_bolus 是否为 None，而不是检查它们是否为 False
            if cho is None or pre_meal_bolus is None:
                 return Response({
                    "status": "error",
                    "message": "缺少必要参数: patientNumber, mealType, cho, preMealBolus 不能为空"
                }, status=status.HTTP_400_BAD_REQUEST)

        # 保存餐食记录
        success, error_message = save_meal_record(
            patient_number=patient_number,
            meal_type=meal_type,
            cho=cho,
            pre_meal_bolus=pre_meal_bolus,
            notes=notes,
            meal_datetime=meal_datetime_obj # 新增：传递解析后的时间对象
        )

        if success:
            return Response({
                "status": "success",
                "message": "餐食记录保存成功"
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                "status": "error",
                "message": error_message
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    except Exception as e:
        return Response({
            "status": "error",
            "message": str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny])
def getMealRecords(request):
    try:
        data = request.data
        patient_number = data.get('patientNumber')
        
        if not patient_number:
            return Response({
                "status": "error",
                "message": "患者编号不能为空"
            }, status=status.HTTP_400_BAD_REQUEST)

        # 获取最近24小时的餐食记录
        twenty_four_hours_ago = timezone.now() - timedelta(hours=24)
        meal_records = PatientMeal.objects.filter(
            patient_number=patient_number,
            time__gte=twenty_four_hours_ago
        ).order_by('-time')

        # 将记录转换为前端需要的格式
        records = []
        for record in meal_records:
            records.append({
                'id': record.id,  # 添加记录ID
                'time': record.time.strftime('%Y-%m-%d %H:%M:%S'),
                'mealType': record.meal_type,
                'cho': record.cho,
                'preMealBolus': record.pre_meal_bolus,
                'notes': record.notes
            })

        return Response({
            "status": "success",
            "data": records
        }, status=status.HTTP_200_OK)

    except Exception as e:
        import traceback
        print(f"Error in getMealRecords: {str(e)}")
        print(traceback.format_exc())
        return Response({
            "status": "error",
            "message": str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny])
def deleteMealRecord(request):
    try:
        data = request.data
        record_id = data.get('recordId')
        
        if not record_id:
            return Response({
                "status": "error",
                "message": "记录ID不能为空"
            }, status=status.HTTP_400_BAD_REQUEST)
            
        try:
            # 查找并删除餐食记录
            meal_record = PatientMeal.objects.get(id=record_id)
            meal_record.delete()
            
            return Response({
                "status": "success",
                "message": "餐食记录删除成功"
            }, status=status.HTTP_200_OK)
            
        except PatientMeal.DoesNotExist:
            return Response({
                "status": "error",
                "message": "未找到指定的餐食记录"
            }, status=status.HTTP_404_NOT_FOUND)
            
    except Exception as e:
        import traceback
        print(f"Error in deleteMealRecord: {str(e)}")
        print(traceback.format_exc())
        return Response({
            "status": "error",
            "message": str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny])
def getBasalRecommendations(request):
    """
    获取患者基础率调整建议的API接口
    
    请求参数：
    {
        "patientNumber": "患者编号",
        "date": "日期(可选，格式为YYYY-MM-DD)",
    }
    
    响应：
    {
        "patient_number": "患者编号",
        "date": "日期",
        "recommendations": [
            {
                "period": "时间段",
                "period_name": "时间段名称",
                "current_basal": 当前基础率(U/hour),
                "recommended_basal": 建议基础率(U/hour),
                "adjustment_pct": 调整百分比,
                "change_direction": "调整方向",
                "reason": "调整原因"
            },
            ...
        ]
    }
    """
    try:
        data = json.loads(request.body.decode('utf-8'))
        patient_number = data.get("patientNumber")
        date_str = data.get("date")  # 日期字符串，格式为YYYY-MM-DD，可选
        
        if not patient_number:
            return Response({"status": "error", "message": "Missing patient number."}, status=400)
        
        # 处理日期参数
        date = None
        if date_str:
            try:
                date = datetime.strptime(date_str, "%Y-%m-%d").date()
            except ValueError:
                return Response({"status": "error", "message": "Invalid date format. Use YYYY-MM-DD."}, status=400)
        
        # 获取基础率调整建议
        result = get_basal_recommendations(patient_number, date)
        
        return Response(result, status=200)
    
    except json.JSONDecodeError:
        return Response({"status": "error", "message": "Invalid JSON format."}, status=400)
    except Exception as e:
        print(f"Error in getBasalRecommendations: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return Response({"status": "error", "message": str(e)}, status=500)

@api_view(['GET'])
@permission_classes([AllowAny])
def getBasalRecommendationsByGet(request):
    """
    通过GET方法获取患者基础率调整建议
    
    URL格式：/api/basal/recommendations/?patient_number=xxx&date=yyyy-mm-dd
    
    参数通过URL查询参数传递：
    - patient_number: 患者编号(必填)
    - date: 日期，格式为YYYY-MM-DD(可选)
    """
    try:
        patient_number = request.GET.get('patient_number')
        date_str = request.GET.get('date')
        
        if not patient_number:
            return Response({
                "status": "error", 
                "message": "Missing patient number."
            }, status=400)
        
        # 处理日期参数
        date = None
        if date_str:
            try:
                date = datetime.strptime(date_str, "%Y-%m-%d").date()
            except ValueError:
                return Response({
                    "status": "error", 
                    "message": "Invalid date format. Use YYYY-MM-DD."
                }, status=400)
        
        # 获取基础率调整建议
        result = get_basal_recommendations(patient_number, date)
        
        return Response(result, status=200)
    
    except Exception as e:
        print(f"Error in getBasalRecommendationsByGet: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return Response({
            "status": "error", 
            "message": str(e)
        }, status=500)

# 用于处理OPTIONS请求的视图
@api_view(['OPTIONS'])
@permission_classes([AllowAny])
def options_view(request, *args, **kwargs):
    """
    处理预检OPTIONS请求
    """
    print(f"收到OPTIONS请求: {request.path}, Headers: {request.headers}")
    
    response = Response()
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
    response["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With, Accept"
    response["Access-Control-Max-Age"] = "86400"  # 24小时
    
    print(f"OPTIONS响应头: {dict(response.headers)}")
    return response

@api_view(['GET'])
@permission_classes([AllowAny])
def admin_create_test_user(request):
    """
    管理员专用视图：创建测试用户并诊断登录问题
    仅在开发环境中使用，生产环境应移除此函数
    """
    try:
        # 创建一个指定的测试用户
        username = 'testuser'
        password = 'testpassword'
        
        # 获取所有现有用户
        print("========== 系统当前用户列表 ==========")
        all_users = User.objects.all()
        user_list = []
        for user in all_users:
            user_info = {
                'id': user.id,
                'username': user.username,
                'is_active': user.is_active,
                'is_staff': user.is_staff,
                'date_joined': user.date_joined
            }
            user_list.append(user_info)
            print(f"用户ID: {user.id}, 用户名: {user.username}, 激活状态: {user.is_active}")
        
        # 检查是否存在SSH123用户（不区分大小写）
        ssh_users = User.objects.filter(username__iexact='ssh123')
        if ssh_users.exists():
            print("找到SSH123用户（不区分大小写）:")
            for user in ssh_users:
                print(f"  - ID: {user.id}, 用户名: {user.username}, 激活状态: {user.is_active}")
                # 确保用户已激活
                if not user.is_active:
                    user.is_active = True
                    user.save()
                    print(f"已激活用户: {user.username}")
        
        # 尝试创建指定的测试用户（如果不存在）
        if not User.objects.filter(username=username).exists():
            user = User.objects.create_user(
                username=username,
                password=password,
                is_active=True
            )
            print(f"已创建测试用户: {username}")
            result = f"已创建测试用户 {username}"
        else:
            test_user = User.objects.get(username=username)
            # 确保用户已激活
            if not test_user.is_active:
                test_user.is_active = True
                test_user.save()
                print(f"已激活测试用户: {username}")
            result = f"测试用户 {username} 已存在"
            
        # 尝试创建ssh123用户（如果不存在）
        if not User.objects.filter(username__iexact='ssh123').exists():
            user = User.objects.create_user(
                username='ssh123',
                password='ssh123',
                is_active=True
            )
            print(f"已创建用户: ssh123")
            result += f", 已创建用户 ssh123"
        
        # 检查数据库连接
        from django.db import connections
        db_status = {}
        for conn_name, conn_config in settings.DATABASES.items():
            try:
                conn = connections[conn_name]
                conn.ensure_connection()
                if conn.is_usable():
                    status = "连接正常"
                else:
                    status = "连接异常"
            except Exception as e:
                status = f"连接错误: {str(e)}"
            
            db_info = {
                "engine": conn_config.get('ENGINE', '未知'),
                "name": conn_config.get('NAME', '未知'),
                "host": conn_config.get('HOST', '未知'),
                "status": status
            }
            db_status[conn_name] = db_info
            print(f"数据库 {conn_name}: {db_info}")
            
        return Response({
            "message": result,
            "users": user_list,
            "database_status": db_status
        })
        
    except Exception as e:
        import traceback
        error_trace = traceback.format_exc()
        print(f"创建测试用户时出错: {str(e)}")
        print(error_trace)
        return Response({
            "error": str(e),
            "traceback": error_trace
        }, status=500)

@api_view(['POST'])
@permission_classes([AllowAny])
def register_and_login(request):
    """
    测试专用视图：注册用户并立即尝试登录
    该视图用于诊断注册后无法登录的问题
    """
    try:
        # 打印诊断信息
        print("==== 开始测试注册并立即登录功能 ====")
        
        # 解析请求数据
        data = parse_request_data(request)
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return Response({
                "status": "error",
                "message": "用户名和密码不能为空"
            }, status=status.HTTP_400_BAD_REQUEST)
            
        print(f"测试使用的用户名: {username}, 密码长度: {len(password)}")
        
        # 步骤1: 检查用户是否已存在
        existing_user = User.objects.filter(username__iexact=username).first()
        if existing_user:
            print(f"用户已存在: ID={existing_user.id}, 用户名={existing_user.username}, 激活状态={existing_user.is_active}")
            # 删除已存在的用户（仅用于测试）
            existing_user.delete()
            print(f"已删除现有用户以进行测试")
            
        # 步骤2: 创建新用户
        print(f"正在创建新用户...")
        try:
            from django.db import transaction
            with transaction.atomic():
                user = User.objects.create_user(
                    username=username,
                    password=password,
                    is_active=True
                )
                print(f"用户创建成功: ID={user.id}, 用户名={user.username}")
            print(f"数据库事务已自动提交 (register_and_login)")
        except Exception as e:
            print(f"创建用户时出错: {str(e)}")
            import traceback
            print(traceback.format_exc())
            return Response({
                "status": "error",
                "message": f"创建用户时出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
        # 步骤3: 直接从数据库加载用户以验证创建是否成功
        try:
            saved_user = User.objects.get(username=username)
            print(f"从数据库验证用户存在: ID={saved_user.id}, 用户名={saved_user.username}, 激活状态={saved_user.is_active}")
        except User.DoesNotExist:
            print(f"严重错误: 刚创建的用户在数据库中不存在!")
            return Response({
                "status": "error",
                "message": "用户创建失败，无法在数据库中找到新创建的用户"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
        # 步骤4: 尝试使用authenticate验证用户
        auth_user = authenticate(username=username, password=password)
        if auth_user:
            print(f"验证成功: authenticate函数确认了用户凭据")
            
            # 步骤5: 生成令牌
            refresh = RefreshToken.for_user(auth_user)
            token = str(refresh.access_token)
            print(f"已生成访问令牌")
            
            return Response({
                "status": "success",
                "message": "用户注册并登录成功",
                "data": {
                    "userId": auth_user.id,
                    "username": auth_user.username,
                    "token": token
                }
            })
        else:
            print(f"验证失败: authenticate函数无法验证用户凭据")
            
            # 尝试使用直接的密码验证
            from django.contrib.auth.hashers import check_password
            if check_password(password, saved_user.password):
                print(f"密码验证成功，但authenticate失败，可能是认证后端配置问题")
            else:
                print(f"密码直接验证也失败，存储的密码可能有问题")
                print(f"存储的密码哈希: {saved_user.password[:10]}...")
                
            return Response({
                "status": "partial_success",
                "message": "用户注册成功，但无法自动登录",
                "data": {
                    "userId": saved_user.id,
                    "username": saved_user.username,
                    "authError": "authenticate函数无法验证用户凭据"
                }
            })
            
    except Exception as e:
        print(f"测试过程中发生错误: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return Response({
            "status": "error",
            "message": f"操作失败: {str(e)}"
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 添加静态文档视图函数
def static_doc_view(request, doc_file):
    """
    提供静态文档文件的视图函数
    
    参数:
    request: HTTP请求对象
    doc_file: 文档文件名
    
    返回:
    包含HTML内容的HTTP响应
    """
    file_path = os.path.join(settings.BASE_DIR, 'app01', 'static', 'docs', doc_file)
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return HttpResponse(content, content_type='text/html; charset=utf-8')
    except FileNotFoundError:
        return HttpResponse(f"文档文件 {doc_file} 未找到", status=404)
    except Exception as e:
        return HttpResponse(f"访问文档时发生错误: {str(e)}", status=500)


